package com.aduerr.v1shouyin.mvp.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.PowerManager;

import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.viewpager.widget.ViewPager;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.PushIP;
import com.aduerr.v1shouyin.entity.TransactionFlowEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.adpter.MyPagerAdapter;
import com.aduerr.v1shouyin.mvp.fragment.Home2Fragment;
import com.aduerr.v1shouyin.mvp.fragment.HomePageFragment;
import com.aduerr.v1shouyin.mvp.receiver.WordstoVoice;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.socket.ClientConnectManager;
import com.aduerr.v1shouyin.socket.HeartBeatHandler;
import com.aduerr.v1shouyin.unioncard.BaseUnionActivity;
import com.aduerr.v1shouyin.unioncard.BaseUnionFragment;
import com.aduerr.v1shouyin.util.MessageEvent;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.yeahka.shouyintong.sdk.action.LockPos;
import com.yeahka.shouyintong.sdk.api.SytApi;
import com.yeahka.shouyintong.sdk.api.SytFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/15 11:15
 * @change
 * @chang time
 * @class describe
 */

public class HomePageActivity extends BaseUnionActivity {

    @BindView(R.id.home_view_pager)
    ViewPager homeViewPager;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.iv_pos_01)
    ImageView ivPos01;
    @BindView(R.id.iv_pos_02)
    ImageView ivPos02;

    private List<BaseUnionFragment> fragmentList = new ArrayList<>();
    private MyPagerAdapter adapter;

    PowerManager pm;
    PowerManager.WakeLock wl;

   /* private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;*/


    @Override
    protected int getLayoutId() {
        return R.layout.activity_home_page;
    }

    @Override
    protected void initBase() {
        super.initView();
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        ivPos01.setImageResource(R.drawable.shape_oval_blue);
        ivPos02.setImageResource(R.drawable.shape_oval_blue2);
        updadeUseData();
        init();
        //        ClientConnectManager.getInstance().init(this);
//        getPushIP();

       /* localBroadcastManager = LocalBroadcastManager.getInstance(this); // 获取实例
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(HeartBeatHandler.BROADCAST_ACTION);
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter); //
        注册本地广播监听器*/
        asKForWakeLock();

    }


    void init() {
        fragmentList.add(new HomePageFragment());
        fragmentList.add(new Home2Fragment());
        adapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentList);
        homeViewPager.setAdapter(adapter);
        homeViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch(position) {
                    case 0:
                        ivPos01.setImageResource(R.drawable.shape_oval_blue);
                        ivPos02.setImageResource(R.drawable.shape_oval_blue2);
                        break;
                    case 1:
                        ivPos01.setImageResource(R.drawable.shape_oval_blue2);
                        ivPos02.setImageResource(R.drawable.shape_oval_blue);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        String company = Hawk.get("company");
        if(company != null && !company.equals("")) {
            /*if (company.length() > 10) {
                tvCompany.setText("欢迎，"+ company.substring(0, 10) + "...");
            } else {*/
            tvCompany.setText("欢迎，" + company);
//            }

        } else {
            tvCompany.setText("......");
        }
        checkLesLocked();

    }


    void updadeUseData() {//更新用户功能模块统计数据
        if(Hawk.get("f_pos") == null) return;
        HashMap<String, String> addParams = new HashMap<>();
        if(Hawk.get("f_order") != null) {
            addParams.put("mkone", Hawk.get("f_order") + "");
        }
        if(Hawk.get("f_refund") != null) {
            addParams.put("mktwo", Hawk.get("f_refund") + "");
        }
        if(Hawk.get("f_trade") != null) {
            addParams.put("mkthree", Hawk.get("f_trade") + "");
        }
        if(Hawk.get("f_print") != null) {
            addParams.put("mkfour", Hawk.get("f_print") + "");
        }
        if(Hawk.get("f_pre") != null) {
            addParams.put("mkfive", Hawk.get("f_pre") + "");
        }
        if(Hawk.get("f_kaquan") != null) {
            addParams.put("mksix", Hawk.get("f_kaquan") + "");
        }
        if(Hawk.get("f_vip") != null) {
            addParams.put("mkseven", Hawk.get("f_vip") + "");
        }
        if(Hawk.get("f_points") != null) {
            addParams.put("mkeight", Hawk.get("f_points") + "");
        }
        if(Hawk.get("f_setting") != null) {
            addParams.put("mknine", Hawk.get("f_setting") + "");
        }
        if(Hawk.get("f_logout") != null) {
            addParams.put("mkten", Hawk.get("f_logout") + "");
        }
        APIRetrofit.getAPIService().postUseData(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object -> {
                }, throwable -> {
                    ToastUtils.showToast(this, "检查网络");
                });


    }

    @Override
    public void onBackPressed() {
    }

    private void getPushIP() {

        APIRetrofit.getAPIService().getPushConfig(Constants.PUSH_URL)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<PushIP>() {
                    @Override
                    public void onNext(PushIP entity) {
                        if(entity.isSuccessed()) {
                            Hawk.put("PUSH_IP", entity.getData().getIP());
                            Hawk.put("PUSH_PORT", entity.getData().getPort());
                            ClientConnectManager.getInstance().connect(HomePageActivity.this);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {

        Boolean b = (Boolean) SharedPreferencesUtils.getParam(HomePageActivity.this,
                "autoprint", false);

        if(!b) return;
        int printPage = (int) SharedPreferencesUtils.getParam(HomePageActivity.this,
                "printpage", 1);
        if(event.message.equals("auto_print")) {//自动打印
            try {
                JSONObject jsonObject = new JSONObject(event.getContent());

                String[] content = new String[20];
                content[0] = jsonObject.getString("orderId");//订单编号
                content[1] = jsonObject.getString("shopName");//门店
                content[2] = jsonObject.getString("siteUserName");//收银员
                content[3] = jsonObject.getString("payType");//支付方式
                content[4] = jsonObject.getString("orderState");//支付状态
                content[5] = jsonObject.getString("payTime");//支付时间
                content[6] = "";//订单金额
                content[7] =jsonObject.getString("payMoney");//实收金额
                content[9] = jsonObject.getString("remark");//订单备注


                TransactionFlowEntity tfEntity = new TransactionFlowEntity();
                String json = new Gson().toJson(content);
                tfEntity.setPrintType(11);
                tfEntity.setJson(json);
                DatabaseManager.getInstance().insert(tfEntity);

                PrinterWrapper.printJPushOrderDetail(true,content,printPage);

            } catch(Exception e) {
                e.printStackTrace();
                Log.d("homePage",e.getMessage()+"");
            }
        }
    }

    private void print(Bitmap logo, JSONObject jsonObject, int printPage) {

        printOrder(logo, jsonObject, printPage);
    }

    private void printOrder(Bitmap logo, JSONObject jsonObject,
                            int printPage) {
        PrinterWrapper.printOrderAuto(logo, jsonObject, printPage);
    }



    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if(wl != null) {
            wl.release();
            wl=null;
        }
        super.onDestroy();
    }

    class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String pushContent = intent.getStringExtra(HeartBeatHandler.MESSAGE);
            if(!pushContent.contains("Notify")) return;
            try {
                JSONObject jsonObject = new JSONObject(pushContent.replace("Notify ",
                        ""));
                WordstoVoice voice = new WordstoVoice();
                voice.toVoice(HomePageActivity.this, jsonObject.getString("Message"));
                if(!jsonObject.getString("Extras").equals("null")) {
                    JSONObject jsonObject2 = new JSONObject(jsonObject.getString(
                            "Extras"));
                    Bitmap bitmap = null;
                    if(jsonObject.getString("payType").equals("微信")) {
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.drawable.print_w);
                    } else if(jsonObject.get("payType").equals("支付宝")) {
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.drawable.print_z);
                    } else {
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.drawable.print_public);
                    }
                    print(bitmap, jsonObject2, 1);
                }
            } catch(JSONException e) {
                e.printStackTrace();
            }
        }
    }


    //申请wakeup锁 ，防止系统休眠导致无法打印


    public void asKForWakeLock() {
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "POS:CPU_WAKEUP");
        if(!wl.isHeld()){
            wl.acquire();
            wl.setReferenceCounted(false);
        }
    }

    /**
     * 首次打开锁定乐刷收银通
     */
    public void checkLesLocked() {
        boolean isLsLocked = Hawk.get("isLsLocked", false);
        if(!isLsLocked) {
            Toast.makeText(App.getApp(),"乐刷收银通独立使用已关闭，按返回键返回到主页面",Toast.LENGTH_LONG).show();
            final SytApi sytApi = SytFactory.createSytIml(this);
            LockPos.Req req = new LockPos.Req();
            req.isLock = true;
            sytApi.sendReq(req);
            Hawk.put("isLsLocked", true);
        }
    }

}
